using System;
using System.Web.Mvc;
using System.Web.Security;
using Animoso.Domain.Data;

namespace Animoso.Web.Controllers
{
    public class AdminController : ApplicationController
    {
        private readonly IUserRepository _repository;

        public AdminController(IUserRepository repository)
        {
            _repository = repository;
        }

        public ActionResult Logon()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
        {
            if (!ValidateLogOn(userName, password))
            {
                return View();
            }
            
            FormsAuthentication.SetAuthCookie(userName, rememberMe);

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Admin");
            }
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "Je moet een gebruikersnaam invoeren.");
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "Je moet een wachtwoord invoeren.");
            }
            if (!ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", "Gebruikersnaam of wachtwoord incorrect.");
            }

            return ModelState.IsValid;
        }

        private bool ValidateUser(string userName, string password)
        {
            return _repository.ValidateUser(userName, password);
        }
    }
}
